import { HsAdminProTable, HsAdminSpin } from '@hs-admin/base-components'

import { Supply_chainList, SupplyChainDetail, SupplyChainexports, SupplyChainexportsall } from '@/api/SupplyChain'

import { Industrcollect, Industrdeletecollect } from '@/api/IndustryChain'

import { Button, Rate, Modal, message, notification, Tooltip, Checkbox } from 'antd'

import Information from './components/Information'

import Search from './components/Search'

import { useImmer } from 'use-immer'

import { memo, useState, useRef, useEffect } from 'react'

import { ServerEmailModal } from '@hs-server/components'

import { export_daily_counts } from '@/api/common'
import { getItem, PERMISSIONS } from '@hs-admin/utils'
import { openCompanyDetail } from 'hs-react-company'

const PAGESIZE = 20

const SupplyChain = () => {
  const InformationModelRef = useRef<any>(null)

  const [totalNumber, settotalNumber] = useState(0)

  const [selectedRowKeys, setselectedRowKeys]: any = useState([])

  const EmailModalRef = useRef<any>(null)

  const [columnsStateMap, setColumnsStateMap]: any = useState({
    action: {
      disable: true,
      show: true,
      fixed: 'left'
    },
    supp_company_name: {
      disable: false,
      show: true,
      fixed: 'left'
    },
    area: {
      disable: false,
      show: true
    },
    industry_nea: {
      disable: false,
      show: true
    },
    supply_product_num: {
      disable: false,
      show: true
    },
    supply_bid_num: {
      disable: false,
      show: true
    },
    supply_report_num: {
      disable: false,
      show: true
    }
  })

  const [api, contextHolder] = notification.useNotification()

  const actionRef: any = useRef()

  const [pagination, setPagination] = useImmer<any>({
    current: 1,
    pageSize: PAGESIZE
  })

  const [data, setData]: any = useState([])

  const [isModalOpen, setModalOpen] = useState(false)

  const [id, setId] = useState('')

  const [title, seTtitle] = useState('供应产品')

  const [SupplyChainrow, setSupplyChainrow] = useState<any>({}) //展示右边搜索的目标公司名称

  const columns = [
    {
      title: '操作',
      key: 'action',
      render: (_name: any, row: any) => (
        <Tooltip placement="topLeft" title={row.is_favorite ? '取消收藏' : '收藏'}>
          <Rate count={1} value={row.is_favorite ? 1 : 0} onChange={() => ChangeRate(row)} />
        </Tooltip>
      ),
      width: 60
    },
    {
      title: '供应商名称',
      dataIndex: 'supp_company_name',
      ellipsis: true,
      render: (_name: any, row: any) => (
        <span className="text-blue cursor-pointer" onClick={() => openCompanyDetail(row.supp_company_code)}>
          {row.supp_company_name}
        </span>
      )
    },
    {
      title: '所在区域',
      dataIndex: 'area',
      width: 180,
      ellipsis: true,
      render: (_: any, row: any) => <span>{`${row.province ?? '--'}/${row.city ?? '--'}/${row.area ?? '--'}`}</span>
    },
    {
      title: '国民经济分类',
      dataIndex: 'industry_nea',
      ellipsis: true
    },
    {
      title: '供应产品（款）',
      dataIndex: 'supply_product_num',
      width: 120,
      render: (_: any, row: any) => (
        <div>
          {row.supply_product_num ? (
            <span className="text-blue cursor-pointer" onClick={() => InformationModel('Product', row.id)}>
              {row.supply_product_num}
            </span>
          ) : (
            <span>--</span>
          )}
        </div>
      )
    },
    {
      title: '中标信息（条）',
      dataIndex: 'supply_bid_num',
      width: 120,
      render: (_: any, row: any) => (
        <div>
          {row.supply_bid_num ? (
            <span className="text-blue cursor-pointer" onClick={() => InformationModel('Bid', row.id)}>
              {row.supply_bid_num}
            </span>
          ) : (
            <span>--</span>
          )}
        </div>
      )
    },
    {
      title: '供应关系相关报告（份）',
      width: 120,
      dataIndex: 'supply_report_num',
      render: (_: any, row: any) => (
        <div>
          {row.supply_report_num ? (
            <span className="text-blue cursor-pointer" onClick={() => InformationModel('supply', row.id)}>
              {row.supply_report_num}
            </span>
          ) : (
            <span>--</span>
          )}
        </div>
      )
    }
  ]

  const [tablecolumns, setTablecolumns]: any = useState([])

  const [tableData, setTableData] = useState([])

  const [counts, setcounts] = useState(0)

  const InformationModel = (type: any, id: any) => {
    let Detailtype = null

    if (type === 'Product') {
      setTablecolumns([
        {
          title: '序号',
          dataIndex: 'index',
          width: 90,
          render: (_: any, _record: any, index: number) => <span>{index + 1}</span>
        },

        {
          title: '产品名称',
          dataIndex: 'supp_product_name',
          ellipsis: true
        },

        { title: '采购金额（万元）', dataIndex: 'supp_amt' },

        { title: '公布时间', dataIndex: 'pub_date' }
      ])
      seTtitle('供应产品')
      Detailtype = 'product'
    }
    if (type === 'Bid') {
      setTablecolumns([
        {
          title: '序号',
          dataIndex: 'index',
          width: 90,
          render: (_: any, _record: any, index: number) => <span>{index + 1}</span>
        },

        { title: '标题', dataIndex: 'title', ellipsis: true },

        { title: '中标金额（万元）', dataIndex: 'supp_amt' },

        { title: '中标时间', dataIndex: 'pub_date' }
      ])
      seTtitle('中标信息')
      Detailtype = 'bid'
    }
    if (type === 'supply') {
      setTablecolumns([
        {
          title: '序号',
          dataIndex: 'index',
          width: 90,
          render: (_: any, _record: any, index: number) => <span>{index + 1}</span>
        },

        { title: '报告名称', dataIndex: 'name', ellipsis: true },

        { title: '公布时间', dataIndex: 'pub_date' }
      ])
      seTtitle('供应关系相关报告')
      Detailtype = 'report'
    }
    InformationModelRef.current.showModal()
    setloading(true)
    return SupplyChainDetail({
      page: pagination.current,
      page_size: pagination.pageSize,
      type: Detailtype,
      id: id
    })
      .then((res: any) => {
        setTableData(res)
        return res
      })
      .finally(() => {
        setloading(false)
      })
  }
  const doRequest = () => {
    setloading(true)
    return Supply_chainList({
      page: pagination.current,
      page_size: pagination.pageSize,
      id: id ?? null
    })
      .then((res) => {
        setData(res.items)
        settotalNumber(res.total)
        return res
      })
      .finally(() => {
        setloading(false)
      })
  }

  useEffect(() => {
    id && doRequest()
  }, [id, SupplyChainrow, pagination])

  //收藏 取消收藏
  const ChangeRate = (value: any) => {
    let params: any = null

    let iscollect: any = Industrcollect

    let mess: any = null

    if (!value.is_favorite) {
      params = {
        company_ids: [value.supp_company_id]
      }
      mess = '收藏成功'
    } else {
      params = value.supp_company_id
      iscollect = Industrdeletecollect

      mess = '取消收藏'
    }

    iscollect(params).then((_res: any) => {
      message.success(mess)
      doRequest()
    })
  }

  const [loading, setloading] = useState(false)

  //勾选的回调
  const doSelect = (record: any, selected: any) => {
    if (selected) {
      setselectedRowKeys((prevState: any[]) => {
        prevState.push(record.id)
        return [...prevState]
      })
    } else {
      setselectedRowKeys((prevState: any[]) => {
        const index = prevState.findIndex((ele: any) => ele === record.id)
        prevState.splice(index, 1)
        return [...prevState]
      })
    }
  }

  const rowSelection = {
    onChange: (_selectedRowKeys: any, _selectedRows: any, info: { type: any }) => {
      if (info.type === 'none') {
        setselectedRowKeys([])
      }
    },
    onSelect: doSelect,
    renderCell: (checked: boolean, record: any) => (
      <div className="flex items-center">
        <Tooltip placement="topLeft" title={checked ? '取消选中' : '选中'}>
          <Checkbox
            checked={checked}
            onChange={(e) => {
              doSelect(record, e.target.checked)
            }}
          />
        </Tooltip>
      </div>
    )
  }

  const addPage = () => {
    if (pagination?.current * pagination.pageSize < totalNumber) {
      setPagination((prev: { current: number }) => {
        prev.current++
      })
    }
  }
  const minusPage = () => {
    setPagination((prev: { current: number }) => {
      prev.current--
    })
  }

  const export_counts = () => {
    export_daily_counts().then((res: any) => {
      res.daily_count = res.daily_count > 0 ? 20000 - res.daily_count : 20000
      setcounts(res.daily_count) // 设置导出数量
    })
  }

  const setIsModalOpen = () => {
    if (selectedRowKeys.length > counts) {
      api.warning({
        message: '超过导出限制',
        description: `今日累计导出超过20000条，剩余${counts}条，请重新选择`
      })
      return
    }

    if (selectedRowKeys.length) {
      if (selectedRowKeys.length < 5000) EmailModalRef.current.showModal()
      if (selectedRowKeys.length > 5000 && selectedRowKeys.length < 10000) setModalOpen(true)
      if (selectedRowKeys.length > 10000) {
        api.warning({
          message: '超过导出限制',
          description: `导出超过单次数量限制10000条，请重新选择`
        })
      }
      if (selectedRowKeys.length > 500) {
        api.warning({
          message: '超过导出限制',
          description: `导出超过单次数量500，请重新选择`
        })
      }
    } else {
      if (totalNumber > counts && counts !== 20000) {
        api.warning({
          message: '超过导出限制',
          description: `今日累计导出超过20000条，剩余${counts}条，请重新选择`
        })
      } else {
        if (totalNumber < 5000) EmailModalRef.current.showModal()
        if (totalNumber > 5000 && totalNumber < 10000) setModalOpen(true)
        if (totalNumber > 10000) {
          api.warning({
            message: '超过导出限制',
            description: `导出超过单次数量限制10000条，请重新选择`
          })
        }
      }
    }
  }

  const success = (item: any) => {
    setPagination((prevPagi: any) => {
      prevPagi.current = 1
      prevPagi.pageSize = PAGESIZE
    })
    setId(item?.mean_table_id)
    setSupplyChainrow(item)
  }

  const handleExport = (obj: any) => {
    let request: any = null
    const params: any = {
      filename: obj.filename,
      columns: [],
      //id 左边企业id
      id: id
    }

    if (selectedRowKeys?.length) {
      columns.map((item: any) => {
        if (columnsStateMap[item.dataIndex]?.show) {
          params.columns.push({
            field: item.dataIndex,
            name: item.title
          })
        }
      })
      params.ids = selectedRowKeys
      request = SupplyChainexports
    } else {
      request = SupplyChainexportsall
    }
    request(params).then((_res: any) => {
      let messages: any = `提交成功,请在${obj.Email}中查看导出结果`
      export_counts() //更新导出数量值
      if (selectedRowKeys.length) {
        if (selectedRowKeys.length > 5000 && selectedRowKeys.length < 10000) messages = `提交成功，请在个人中心中查看审核结果`
      } else {
        if (totalNumber > 5000 && totalNumber < 10000) messages = `提交成功，请在个人中心中查看审核结果`
      }
      message.success(messages)
      actionRef.current.clearSelected()
      setselectedRowKeys([])
      setModalOpen(false)
    })
  }

  const exportonok = () => {
    setModalOpen(false)
    EmailModalRef.current.showModal()
  }

  useEffect(() => {
    export_counts()
  }, [])

  const permissions = getItem(PERMISSIONS) || []

  return (
    <div className="bg-white h-100%">
      {/* search  title */}
      {/* body */}
      <div className="flex h-100% w-100%">
        <div className="h-88%">
          <Search success={success} />
        </div>
        <div className="overflow-auto h-100% w-100%">
          <div className="h-4% font-bold p-t-15px p-l-10px">
            找到 <span className="font-bold text-lg">{SupplyChainrow?.company_name ?? ''}</span> 供应商信息
          </div>
          <div className="flex justify-between items-center">
            <div className="flex mx-20px items-center p-t-48px">
              <Button type="primary" className="mr-10px" onClick={minusPage} disabled={pagination.current === 1}>
                上一页
              </Button>
              <div className="mr-20px">{`${(pagination.current - 1) * pagination.pageSize + 1} - ${pagination.current * pagination.pageSize}`}条</div>

              <Button type="primary" onClick={addPage} disabled={pagination.current * pagination.pageSize >= totalNumber}>
                下一页
              </Button>
            </div>
            {permissions.includes('sg.export.limit.20000') && (
              <div className="m-10px flex flex-col">
                {contextHolder}
                <Button type="primary" onClick={setIsModalOpen}>
                  {selectedRowKeys.length ? `导出${selectedRowKeys.length}` : '全部导出'}
                </Button>
                <div>今日还能导出{counts}条</div>
              </div>
            )}
          </div>
          {loading && <HsAdminSpin />}
          <HsAdminProTable
            id="J-supply-chain-table"
            actionRef={actionRef}
            rowSelection={{
              hideSelectAll: true,
              type: 'checkbox',
              selectedRowKeys,
              ...rowSelection
            }}
            columns={columns}
            rowKey="id"
            dataSource={data}
            columnsState={{ value: columnsStateMap, onChange: setColumnsStateMap }}
            pagination={false}
            scroll={{ x: 800, y: 600 }}
          />
        </div>
      </div>
      <Information ref={InformationModelRef} columns={tablecolumns} data={tableData} title={title} cellFontSize={16} maxHeight={200} />
      <ServerEmailModal ref={EmailModalRef} success={handleExport} title={'导出数据'}></ServerEmailModal>
      <Modal
        title={'单次导出超出5000条，需要通过审批才能导出，是否继续？'}
        open={isModalOpen}
        onCancel={() => setModalOpen(false)}
        onOk={exportonok}></Modal>
    </div>
  )
}
export default memo(SupplyChain)
